package c.a.md.androidvideo.gles;

import android.content.Context;
import android.opengl.GLES20;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import c.a.md.androidvideo.gles.util.BufferTransformUtil;
import c.a.md.androidvideo.gles.util.ShaderUtils;

/**
 * Created by ytf on 2018/10/24.
 * Description:
 */
public class Triangle implements IGLBaseShape
{
    private static final int COORDS_PER_VERTEX = 3;

    private final String vertexShaderCode =
            "attribute vec4 vPosition;" +
                    "void main() {" +
                    "gl_Position = vPosition;" +
                    "}";

    private final String fragmentShaderCode =
            "precision mediump float;" +
                    "uniform vec4 vColor;" +
                    "void main() {" +
                    "gl_FragColor = vColor;" +
                    "}";

    private float color[] = {255, 0, 0, 1.0f};
    private int mColorHandle;
    private float triangleCoords[] = {
            0.0f, 0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            0.5f, -0.5f, 0.0f
    };

    private FloatBuffer verticesBuffer;


    private int mProgram;
    private int mPositionHandle;
    private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
    private final int vertexStride = COORDS_PER_VERTEX * 4;

    public Triangle()
    {
        int vs = ShaderUtils.createShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
        int fs = ShaderUtils.createShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
        mProgram = ShaderUtils.handleProgram(vs, fs);
        verticesBuffer = BufferTransformUtil.floatBufferUtil(triangleCoords);
    }

    @Override
    public void onDraw()
    {
        GLES20.glUseProgram(mProgram);
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT,
                false, vertexStride, verticesBuffer);
        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
        GLES20.glUniform4fv(mColorHandle, 1, color, 0);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }
}
